package com.zhouyer.study.service.impl;

import com.zhouyer.study.entity.ToEmail;
import com.zhouyer.study.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 发送邮件实现逻辑
 *
 * @author zhouyao
 * @version 1.0
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {
    // 邮件发送方
    @Value("${spring.mail.username}")
    private String sendName;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public boolean sendSimpleEmail(ToEmail toEmail) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sendName);
        simpleMailMessage.setTo(toEmail.getToUser());
        simpleMailMessage.setSubject(toEmail.getSubject());
        simpleMailMessage.setText(toEmail.getContent());
        try {
            mailSender.send(simpleMailMessage);
            return true;
        } catch (Exception e) {
            log.error("给【" + toEmail.getToUser() + "】发送邮件失败", e);
        }
        return false;
    }
}
